package com.zztl.infiniteBand.net


import android.content.Context
import com.zztl.infiniteBand.R
import com.zztl.infiniteBand.eventbus.TokenLoseEvent
import com.zztl.infiniteBand.model.BaseResponseBean
import com.zztl.infiniteBand.storage.BillPreference
import com.zztl.infiniteBand.storage.PreferenceKeys
import com.zztl.infiniteBand.ui.view.dialog.DismissListener
import com.zztl.infiniteBand.ui.view.dialog.LoadingDialog
import com.zztl.infiniteBand.util.NetworkUtil
import com.zztl.infiniteBand.util.UiUtils
import com.zztl.infiniteBand.util.toast
import org.greenrobot.eventbus.EventBus
import rx.Subscriber

/**
 * @desc
 * @auth ${user
 * @time 2018/6/4  14:17
 */
abstract class FilterSubscriber<T>(internal var mContext: Context) : Subscriber<T>() {
  private val mLoadingDialog by lazy {
      LoadingDialog.Builder(mContext)
              .setShowMessage(false)
              .setCancelable(true)
              .setDismissListener(object :DismissListener{
                  override fun dismiss(){
                      onCompleted()
                      if (!isUnsubscribed) {
                          unsubscribe()
                      }
                  }
              }).create()
  }

    override fun onStart() {
        super.onStart()
        mLoadingDialog.show()
        if (!NetworkUtil.isNetworkAvailable) {
            mLoadingDialog.cancle()
            UiUtils.context.toast("网络不可用")
            fail()
            onCompleted()
        }
    }

    override fun onCompleted() {

    }

    override fun onError(e: Throwable) {
        mLoadingDialog.cancle()

        fail()
        if (e is Exception) {
            //访问获得对应的Exception
            onError(ExceptionHandle.handleException(e))
        } else {
            //将Throwable 和 未知错误的status code返回
            onError(ExceptionHandle.ResponeThrowable(e, ExceptionHandle.ERROR.UNKNOWN))
        }
    }

    override fun onNext(t: T) {
        mLoadingDialog.cancle()

        if (t is BaseResponseBean<*>) {
            if ((t as BaseResponseBean<*>).code != BaseResponseBean.OK) {
                if ((t as BaseResponseBean<*>).code == -99995 || (t as BaseResponseBean<*>).code == -99996) {
                    BillPreference.putApp(PreferenceKeys.LOGINED.name, false)
//                    ToastUtils.show(mContext, UiUtils.getString(R.string.登录已过期请重新登录))
                    mContext.toast(UiUtils.getString(R.string.登录已过期请重新登录))
                    EventBus.getDefault().post(TokenLoseEvent())
                } else {
                  mContext.toast((t as BaseResponseBean<*>).message!!)
                }
                fail()
            } else {
                success(t)
            }
        }
    }

    protected abstract fun success(t: T)

    open fun fail() {}


    fun onError(responeThrowable: ExceptionHandle.ResponeThrowable) {
//        ToastUtils.show(mContext, responeThrowable.message!!)
    }


}
